<template>
  <div class="container-fluid w-75 mx-auto pt-5">
    <todo_Header @updateHeaderChecked="updateFatherChecked" @updateHeaderInput="updateFatherInput"
      :allChecked="allChecked"></todo_Header>

    <ul class="list-group mt-4">

      <todo_Item @updateFatherItem="updateFatherItem" @delItem="delItem" v-for="item in renderList" :key="item.id" :todoContent="item.text"
        :checked="item.checked" :todoId="item.id"></todo_Item>

    </ul>

    <todo_Footer :event="residue" @updateFatherlist="updateFatherlist" @clearFatherlist="clearFatherlist"></todo_Footer>
  </div>
</template>

<script>
import todo_Header from "./todo-header.vue"
import todo_Item from "./todo-item.vue"
import todo_Footer from "./todo-footer.vue"
export default {
  components: {
    todo_Header,
    todo_Item,
    todo_Footer,
  },
  data() {
    return {
      todolist: [
        { id: 100, text: "月薪200K", checked: false, },
        { id: 101, text: "买辆保时捷", checked: false, },
        { id: 102, text: "买海景房", checked: false, },
      ],
      // 默认全选
      status: 0,
    }
  },
  computed: {
    allChecked() {
      return this.todolist.length ? this.todolist.every(item => item.checked) : false;
    },
    // 模糊选择，过滤数据
    renderList() {
      switch(this.status) {
        case 0:
          return this.todolist
        case 1:
          return this.todolist.filter(item => item.checked === false)
        case 2:
          return this.todolist.filter(item => item.checked === true)
      }
    },
    residue() {
      return this.todolist.filter(item => item.checked === false).length
    },
  },
  methods: {
    updateFatherChecked(value) {
      this.todolist.forEach(item => item.checked = value)
    },
    updateFatherInput(value) {
      // 新增id需要读取原数组的id，因为无法读取null的属性，需要先判断数组的长度
      const id = this.todolist.length ? this.todolist[this.todolist.length - 1].id + 1 : 1;
      this.todolist.push({ id, text: value, checked: false })
    },
    updateFatherItem(value, id) {
      // 将子组件的数据同步到父组件todolist[index].checked
      const index = this.todolist.findIndex(item => item.id === id)
      this.todolist[index].checked = value
    },
    delItem(value) {
      const index = this.todolist.findIndex( item => item.id === value)
      this.todolist.splice(index,1)
    },
    updateFatherlist(value) {
      // 将子组件的数据同步到父组件的数据status
      this.status = value
    },
    clearFatherlist() {
      this.todolist = this.todolist.filter(item => item.checked === false)
    }
  }
};
</script>

<style>
</style>